<?php
namespace Backend\Models\Car;

use Backend\Models\Base;

class Kulala extends Base
{
    public function initialize()
    {
        parent::initialize();
    }

    public function getSource()
    {
        return 'daishu_kulala_member_bind';
    }

    public function gets($limit, $offset)
    {
        $query = $this->select('mb.id,mb.drivce_num,kb.name as b_name,ks.name as s_name,km.name as m_name,mc.prov_key as m_pro,mc.num as m_no')
                      ->addFrom(self::class, 'mb')
                      ->leftJoin(KulalaMemberCar::class, 'mb.kcm_id = mc.id', 'mc')
                      ->leftJoin(KulalaSeries::class, 'mc.series = ks.id', 'ks')
                      ->leftJoin(KulalaModels::class, 'mc.module = km.id', 'km')
                      ->leftJoin(KulalaBrands::class, 'mc.brand = kb.id', 'kb')
                      ->limit($limit, $offset)
                      ->orderBy('mb.id DESC');
        try {
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result)) {
                $out = [];
                foreach ($result as $k => $v) {
                    $out[$k] = [
                        'id'         => $v['id'],
                        'drivce_num' => $v['drivce_num'],
                        'car_name'   => $v['b_name'] . $v['s_name'] . $v['m_name'],
                        'p_num'      => $v['m_pro'] . $v['m_no']
                    ];
                }
                return $out;
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function getCount()
    {
        $query = $this->select('count(*) AS cnt')->from(self::class);
        try {
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result) && count($result) > 0) {
                return $result[0]['cnt'];
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function get($id)
    {
        $query = $this->select('kc_id')->where('id=:id:', ['id' => $id])->from(self::class);
        try {
            $result = $query->getQuery()->execute()->toArray();
            if ($result !== false && is_array($result) && count($result) > 0) {
                return $result[0];
            }
        } catch (\Exception $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

}
